import axios from "axios"
import store from "@/stores";
import cache from '@/utils/cache'

axios.defaults.withCredentials = true
// @ts-ignore
axios.defaults.baseURL = window.apiGateway;

/**
 * 获取用户的Token
 * @param IsInit 是否是系统初始化，初始登陆时不需要处理跳转
 */
export async function getUserToken(IsInit?: boolean) {
    return axios.get('/webserver/user/token').then(async (res) => {
        if (res.status == 401) {
            cache.removeToken();
            if (!IsInit) {
                console.log("auth跳转首页")
                //window.location.href = "/#/login";
                window.location.reload();
            }
            return Promise.reject()
        } else if (res.status == 200) {
            if (res.data.status == 401) {
                if (res.data?.data?.indexOf("http") > -1) {
                    let url =res.data.data;
                    const urlIns = new URL(url);
                    //如果OSS客户端和OSS服务端没有部署在一起，也没有开启相对目录，也没有开启HTTPS,则要替换IP，服务端IP要用Nginx代理，或本地开发代理
                    if(!url.startsWith("https")&&urlIns.host!=window.location.host){
                        url=url.replace(urlIns.host,window.location.host);
                    }
                    sessionStorage.setItem("redirectUri", url);
                }
                cache.removeToken();
                if (!IsInit) {
                    console.log("auth跳转首页")
                    //window.location.href = "/#/login";
                    window.location.reload();
                }
                return Promise.reject()
            } else {
                console.log("写入token")
                //const token = res.data.data;
                await store.userStore.setToken(res.data.data);
                //localStorage.setItem('token', JSON.stringify(res.data.data));
                return Promise.resolve();
            }
        }
    })
}
